import { getUserInfo,logout } from '@/api/common/login'
import bus from '@/framework/plugins/bus'

export async function loginSuccess(token,toUrl){
	uni.setStorageSync("token",token)
	const userInfo = await getUserInfo()
	const user = userInfo.user
	uni.setStorageSync("user",user)
	bus.$emit('loginSuccess',user)
	uni.showToast({
		title: '登录成功',
		mask: true,
		icon: 'none'
	})
	if(!toUrl){
		uni.navigateBack({
		    delta: 1  
		});
		return
	} 
	uni.navigateTo({
	  url: toUrl
	});
}

export async function clearLoginInfo(){
	uni.removeStorageSync("token")
	uni.removeStorageSync("user")
}

export async function getLoginUser(){
	const token = uni.getStorageSync("token");
	let user = null
	if(token){
		const userInfo = await getUserInfo()
		user = userInfo.user
	}
	return user
}

export async function logoutAndClearUser(){
	await logout()
	await clearLoginInfo()
}